﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WhutDoomCheck.Server.Configs;

namespace WhutDoomCheck.Server.Services
{
    public class AccessTokenService
    {
        public AccessTokenService(TokenFactoryConfiguration configuration)
        {
            this.configuration = configuration;
        }

        private readonly TokenFactoryConfiguration configuration;

        public int RefreshTokenExpireBefore => configuration.RefreshTokenBefore;

        private string CreateToken(IEnumerable<Claim> claims, string userId, DateTime expires)
        {
            claims = claims.Append(new Claim(ClaimTypes.NameIdentifier, userId));
            var credentials = new SigningCredentials
                (
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.SigningKey)),
                    SecurityAlgorithms.HmacSha256
                );
            var token = new JwtSecurityToken
                (
                    issuer: configuration.Issuer,
                    audience: configuration.Audience,
                    notBefore: DateTime.Now,
                    expires: expires,
                    claims: claims,
                    signingCredentials: credentials
                );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public string CreateAccessTokenForStudent(string user)
        {
            var claim = Enumerable.Empty<Claim>().Append(new Claim("UserType", "Student"));
            var expires = DateTime.Now.AddMinutes(configuration.AccessTokenExpire);
            return CreateToken(claim, user, expires);
        }

        public string CreateAccessTokenForTeacher(string user)
        {
            var claim = Enumerable.Empty<Claim>().Append(new Claim("UserType", "Teacher"));
            var expires = DateTime.Now.AddMinutes(configuration.AccessTokenExpire);
            return CreateToken(claim, user, expires);
        }

        public string CreateAccessTokenForSchool(string user)
        {
            var claim = Enumerable.Empty<Claim>().Append(new Claim("UserType", "School"));
            var expires = DateTime.Now.AddMinutes(configuration.AccessTokenExpire);
            return CreateToken(claim, user, expires);
        }
    }
}
